package com.lcicl.reggie.service.impl;
/*
  Date: 2023/11/01
  Author: Luochao
  Description:
*/

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcicl.reggie.common.BaseContext;
import com.lcicl.reggie.common.CustomException;
import com.lcicl.reggie.entity.*;
import com.lcicl.reggie.mapper.OrderMapper;
import com.lcicl.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    UserService userService;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    AddressBookService addressBookService;

    @Override
    public void submit(Orders order) {

        // 查询购物车
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> shoppingCarWrapper = new LambdaQueryWrapper<>();
        shoppingCarWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCarWrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 查询用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("用户不存在，不能下单");
        }
        //查询地址簿
        if (order.getAddressBookId() == null){
            throw new CustomException("地址不存在，不能下单");
        };
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());

        // 生成订单号
        long id = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);  //计算总价
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((shoppingCart) -> {
            OrderDetail orderDetail = new OrderDetail();//订单明细
            BeanUtils.copyProperties(shoppingCart, orderDetail,"id");
            orderDetail.setOrderId(id);
            amount.getAndAdd(shoppingCart.getAmount().multiply(BigDecimal.valueOf(shoppingCart.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());

        // 插入订单表
        order.setNumber(String.valueOf(id));
        order.setStatus(2);
        order.setUserId(userId);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setPayMethod(1);//支付方式
        order.setAmount(BigDecimal.valueOf(amount.get()));//订单总金额
        order.setPhone(addressBook.getPhone());//收货手机号

        String cityName = addressBook.getCityName();
        String address = (cityName ==null?"":cityName) + addressBook.getDetail();
        order.setAddress(address);//收货地址

        order.setUserName(user.getName());//下单人姓名
        order.setConsignee(addressBook.getConsignee());//收货人姓名
        orderService.save(order);

        // 插入订单明细表
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.remove(shoppingCarWrapper);


    }
}
